/**
 * 按需维保审批
 */
import {Component, NgModule, OnInit} from "@angular/core";

import {Router} from "@angular/router";
import {NzModalService, NzModalSubject, NzNotificationService, UploadFile} from "ng-zorro-antd";
import {HttpServcie} from "../../../service/http.service";
import {Config} from "../../../service/config";
import {DemandMaintenanceBean} from "../bean/demandMaintenance.bean";
import * as moment from "moment";

@Component({
  selector: "demandMaintenance-approval",
  templateUrl: "demandMaintenance-approval.html",
  styleUrls: ["demandMaintenance-approval.scss"]
})

export class DemandMaintenanceApproval {
  constructor(
    private httpService: HttpServcie,
    private router: Router,
    private _notification: NzNotificationService,
    private nsub: NzModalSubject,
    private modalService: NzModalService
  ) {
    this.user = JSON.parse(window.localStorage.getItem("user"));
  }

  //业务参数
  applyStatus = Config.APPLY_STATUS;  //按需维保申请状态
  demandMaintenance : DemandMaintenanceBean = new DemandMaintenanceBean();
  user : any;
  data: Array<any> = [];
  partyType : string = "";
  partyLevel : string; //监管单位级别
  isShowButton : any = false;
  startDate : string = "";
  endDate : string = "";

  //审批使用参数
  showFlag : boolean;
  tempBean : DemandMaintenanceBean = new DemandMaintenanceBean();
  //返回的集合
  dataList : any = [];

  //多选框参数
  allChecked: any = false;
  indeterminate: any = false;
  updateData: any = {};
  total = 0;

  //模态框参数
  modelTitle : string = "";
  modal: any = 0;
  currentModal: NzModalSubject;

  //其他参数
  config = Config;

  ngOnInit(){
    this.user = JSON.parse(window.localStorage.getItem("user"));
    this.partyLevel = this.user.partyLevel;
    this.partyType = this.user.partyType;
    this.demandMaintenance.pageSize = 10;
    this.demandMaintenance.currentPage = 1;
    this.query();
  }

  query(){
    if(this.demandMaintenance.startDate){
      this.demandMaintenance.startDate = moment(this.demandMaintenance.startDate).format("YYYY-MM-DD");
    }
    if(this.demandMaintenance.endDate){
      this.demandMaintenance.endDate = moment(this.demandMaintenance.endDate).format("YYYY-MM-DD");
    }
    if(this.partyLevel == '2'){ //当前监管单位是区级单位
      this.demandMaintenance.parentPartyId = this.user.partyId;
      this.isShowButton = true;
      this.demandMaintenance.applyStatus = '1';
    }
    if(this.partyLevel == '1'){ //当前监管单位是市级单位
      this.demandMaintenance.parentParentPartyId = this.user.partyId;
      this.isShowButton = false;
      this.demandMaintenance.applyStatus = '2';
    }
    this.httpService.queryDemandMaintence(this.demandMaintenance).subscribe(data =>{
      if(data.status == '200'){
        this.dataList = data.data.list;

      }else{
        this._notification.create('error', '错误提示', data.message);
      }
    });
  }

  /**
   * 查看电梯详情
   */
  detail(data){
    this.router.navigate(["/home/demandMaintenanceElevator",{"elevatorIds" : data.elevatorIds}]);
  }

  /**
   * 1：下载服务申明文件，2：下载承诺书照片
   */
  downloadFile(data,flag){
    if(flag == 1){
      if (!data.maintenceServiceStatementDoc) {
        this._notification.create("error", "提示", "没有文件");
        return;
      }
      let list: any = data.maintenceServiceStatementDoc.split(",")
      for (let i = 0; i < list.length; i++) {
        let name1 = '培训服务自我申明' + (i + 1) + "." + list[i].split(".")[1];
        this.download(list[i], name1);
      }
    }

    if(flag == 2){
      if (!data.letterOfCommitmentDoc) {
        this._notification.create("error", "提示", "没有文件");
        return;
      }
      let list: any = data.letterOfCommitmentDoc.split(",")
      for (let i = 0; i < list.length; i++) {
        let name1 = '承诺书' + (i + 1) + "." + list[i].split(".")[1];
        this.download(list[i], name1);
      }
    }
  }

  download(url, name) {
    let link = document.createElement('a');
    let body = document.querySelector('body');

    this.getBlob(this.config.IP + this.config.API.getUpload + url).then(blob => {
      link.href = window.URL.createObjectURL(blob);
      link.download = name;
      // fix Firefox
      link.style.display = 'none';
      body.appendChild(link);
      link.click();
      body.removeChild(link);
      window.URL.revokeObjectURL(link.href);
    });
  }

  getBlob(url) {
    return new Promise(resolve => {
      const xhr = new XMLHttpRequest();
      xhr.open('GET', url, true);
      xhr.responseType = 'blob';
      xhr.onload = () => {
        if (xhr.status === 200) {
          resolve(xhr.response);
        }
      };
      xhr.send();
    });
  }

  //审核
  showDetail(title,content, footer,data) {
    this.tempBean = data;
    if(data.applyStatus == '1'){
      this.showFlag = false;
    }else{
      this.showFlag = true;
    }
    this.currentModal = this.modalService.open({
      title: "查看审核详情",
      content: content,
      width: 1000,
      footer: true,
      style: {
        top: "20px"
      }
    });
  }

  quit(){
    this.currentModal.destroy();
  }

  submit(){
    let demandMaint: DemandMaintenanceBean = new DemandMaintenanceBean();
    demandMaint.id = this.tempBean.id;
    demandMaint.applyStatus = this.tempBean.applyStatus; //提交审批后，状态变成审批中
    demandMaint.parentPartyId = this.tempBean.parentPartyId;
    demandMaint.userPartyId = this.tempBean.userPartyId;
    demandMaint.remarks = this.tempBean.remarks;
    if(demandMaint.applyStatus == '2'){ //审批通过时，传入按需维保的配置的电梯与维保周期
      demandMaint.elevatorIds = this.tempBean.elevatorIds;
      demandMaint.maintenanceCycle = this.tempBean.maintenanceCycle;
    }
    this.httpService.updateDemandMaintence(demandMaint).subscribe(data => {
      if (data["status"] == "200") {
        this._notification.create("success", "提示", "提交成功！");
        this.currentModal.destroy();
        this.query();
      }else{
        this._notification.create("error", "错误提示", "提交失败！");
      }
    });
  }
  /**
   * 是否中止按需维保
   */
  /**
   * 是否中止按需维保
   */
  isSuspend(data){
    let demandMaintenance : DemandMaintenanceBean = new DemandMaintenanceBean();
    demandMaintenance.id = data.id;
    demandMaintenance.applyStatus = '4';
    demandMaintenance.maintenancePartyId = data.maintenancePartyId;
    demandMaintenance.userPartyId = data.userPartyId;
    demandMaintenance.parentPartyId = data.parentPartyId;
    demandMaintenance.elevatorIds = data.elevatorIds;
    this.httpService.updateDemandMaintence(demandMaintenance).subscribe(data => {
      if (data["status"] == "200") {
        this._notification.create("success", "提示", "按需维保已中止！");
        this.query();
      }else{
        this._notification.create("error", "错误提示", "中止操作失败！");
        return;
      }
    });
  }

  displayDataChange($event){
    this.dataList = $event;
    this.refreshStatus();
  }

  checkAll(value){
    if (value) {
      this.dataList.forEach(data => {
        if (!data.disabled) {
          data.checked = true;
        }
      });
    } else {
      this.dataList.forEach(data => data.checked = false);
    }
    this.refreshStatus();
  }

  //重置选择框
  refreshStatus() {
    const allChecked = this.dataList.every(
      value => value.disabled || value.checked
    );
    const allUnChecked = this.dataList.every(
      value => value.disabled || !value.checked
    );
    this.allChecked = allChecked;
    this.indeterminate = !allChecked && !allUnChecked;
  }

  //分页处理
  nzPageSizeChange(event){
    this.demandMaintenance.pageSize = event;
    this.demandMaintenance.currentPage = 1;
    this.query();
  }

  nzPageIndexChange(event){
    this.demandMaintenance.currentPage = event;
    this.query();
  }

  nzPageIndexClickChange(event){
    this.demandMaintenance.currentPage = event;
    this.query();
  }

  //添加返回
  addCall(event) {
    this.currentModal.destroy();
    this.query();
  }
  // 查询面板
  panels = {
    active: true,
    name: "查询",
    disabled: false,
    childPanel: [
      {
        active: false,
        name: "查询"
      }
    ]
  };

}
